package com.lfxfs;

import com.lfxfs.soap.request.BillFormatCustomizeRepire;
import com.lfxfs.soap.request.CElement;
import com.lfxfs.soap.request.DBSET;
import com.lfxfs.soap.request.Order;
import com.lfxfs.soap.utils.SoapUtil;
import com.lfxfs.soap.utils.XmlUtils;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.message.RPCElement;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.axis.soap.SOAPFactoryImpl;
import org.apache.commons.lang.StringEscapeUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.rpc.ParameterMode;
import javax.xml.soap.*;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainClass {


    public static void main1(String[] args) {
        Order<BillFormatCustomizeRepire> order = new Order();
        order.setServiceCode("SVC2001");
        order.setSource("WX");
        order.setTarget("sdfasdf");
        List<BillFormatCustomizeRepire> billFormatCustomizeRepireList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            BillFormatCustomizeRepire billFormatCustomizeRepire = new BillFormatCustomizeRepire();
            billFormatCustomizeRepire.setAppNo("123131");
            billFormatCustomizeRepire.setCancelDate(new Date());
            billFormatCustomizeRepire.setCancelRean("测试机器");
            order.setData(billFormatCustomizeRepire);
            billFormatCustomizeRepireList.add(billFormatCustomizeRepire);
        }
        doTranferObjectToSOAP(order);
        //order.setDatas(billFormatCustomizeRepireList);
        System.out.println(XmlUtils.convertToXml(order));
        Order<BillFormatCustomizeRepire> order1 = (Order<BillFormatCustomizeRepire>) XmlUtils.convertXmlStrToObject(Order.class,doGetOrderXmlStr());
        System.out.println(order1.getData().getAppNo());


        DBSET dbset = new DBSET();
        List<CElement> cElements = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            CElement cElement = new CElement();
            cElement.setAppNo("NAME"+i);
            cElement.setValue("value"+i);
            cElements.add(cElement);
        }
        dbset.setcElementList(cElements);
        doTranferObjectToSOAP(dbset);
        System.out.println(XmlUtils.beanToXml(dbset));
        DBSET dbset1 = new DBSET();
        dbset1 = XmlUtils.xmlToBean(doGetDBSETXmlStr(),DBSET.class);
        System.out.println(dbset1.getcElementList().get(0).getValue());;
        System.out.println(doGenerateSOAPXML("getDate",XmlUtils.convertToXml(order)));
       SoapUtil.sendSoapXml("{}","SVN20101","SVC20191","V202010101","20202020181010","20201019101","N20202","BRAN20202","USER2010110","TOKEN-220181818","SAFDSAFASFD",
                "BRANCHNOO202020","DEST202020");
        //callMethod("http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx","http://WebXml.com.cn/","qqCheckOnline",doGetCheckOnline());
    }

    public static String doGetOrderXmlStr(){
        String str = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<ORDER>\n" +
                "    <servicecode>SVC2001</servicecode>\n" +
                "    <source>WX</source>\n" +
                "    <target>sdfasdf</target>\n" +
                "    <data>\n" +
                "        <appNo>123131</appNo>\n" +
                "        <cancelDate>2020-05-23T11:02:58.691+08:00</cancelDate>\n" +
                "        <cancelRean>测试机器</cancelRean>\n" +
                "    </data>\n" +
                "</ORDER>";
        return str;
    }

    public static String doGetCheckOnline(){
        String str = "<qqCheckOnline xmlns=\"http://WebXml.com.cn/\">\n" +
                "      <qqCode>371527878</qqCode>\n" +
                "    </qqCheckOnline>";
        return str;
    }

    public static String doGetDBSETXmlStr(){
        String str = "<DBSET>\n" +
                "    <R>\n" +
                "        <C N=\"NAME0\">value0</C>\n" +
                "        <C N=\"NAME1\">value1</C>\n" +
                "        <C N=\"NAME2\">value2</C>\n" +
                "        <C N=\"NAME3\">value3</C>\n" +
                "        <C N=\"NAME4\">value4</C>\n" +
                "    </R>\n" +
                "</DBSET>";
        return str;
    }

    public static String toFormatedXML(Document object) throws Exception {
        Document doc = (Document) object;
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transFormer = transFactory.newTransformer();
        transFormer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        DOMSource domSource = new DOMSource(doc);

        StringWriter sw = new StringWriter();
        StreamResult xmlResult = new StreamResult(sw);

        transFormer.transform(domSource, xmlResult);

        return sw.toString();

    }


    public static void main(String[] args){
        String str = "<ValidateEmailAddress xmlns=\"http://WebXml.com.cn/\">\n" +
                "      <theEmail>2@as.com</theEmail>\n" +
                "    </ValidateEmailAddress>";
        callMethod("http://www.webxml.com.cn/WebServices/ValidateEmailWebService.asmx","http://WebXml.com.cn/","ValidateEmailAddress",str);
    }
    /**
     * 调用webservice服务
     * @param url url, 不需要带 ?wsdl 后缀
     * @param targetNamespace 对应xml文件的targetNamespace
     * @param methodName 方法名
     * @return map
     */
    public static String callMethod(String url, String targetNamespace, String methodName, String xmlParam) {
        try {
            Service service = new Service();
            Call call = (Call) service.createCall();
            //加入如下的方法:在调用的时候直接写
            call.setUseSOAPAction(true);
            call.setSOAPActionURI("http://WebXml.com.cn/ValidateEmailAddress");
            //call.addParameter("in0", XMLType.XSD_STRING, ParameterMode.IN);
            //call.setReturnType(XMLType.XSD_STRING);
            call.setTargetEndpointAddress(url);
            //设置要调用哪个方法
            call.setOperationName(new QName(targetNamespace, methodName));
            //设置参数名称
            //要返回的数据类型
            // 调用服务，并传参
            String webServiceResult = (String)call.invoke(new Object[]{xmlParam});
            System.out.println(webServiceResult);
            return webServiceResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static SOAPBodyElement doGenerateElement(String namespace, String methodName, Object[] args){
        return new RPCElement(namespace, methodName, args);
    }

    public static String doGenerateSOAPXML(String method,String param){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wec=\"http://wechat.psucs.com\">\n" +
                "    <soapenv:Header/>\n" +
                "    <soapenv:Body>\n")
                .append("        <wec:")
                .append(method)
                .append(">\n" +
                "            <!--Optional:-->\n" +
                "            <wec:msg>\n").append(param).append("\n</wec:msg>\n" +
                "        </wec:").append(method).append(">\n" +
                "    </soapenv:Body>\n" +
                "</soapenv:Envelope>");
        return stringBuffer.toString();
    }


    public static String doTranferObjectToSOAP(Object o){
        try {
            Document document = XmlUtils.converToDocument(o);
            Element rootElement = document.getDocumentElement();
            //创建soap工厂
            SOAPFactory soapFactory = SOAPFactory.newInstance();

            SOAPMessage soapMessage = MessageFactory.newInstance(javax.xml.soap.SOAPConstants.DEFAULT_SOAP_PROTOCOL).createMessage();
            SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
            //自定义前缀
            soapEnvelope.setPrefix("soapenv");
            soapEnvelope.removeNamespaceDeclaration("SOAP-ENV");
            soapEnvelope.addNamespaceDeclaration("wec", "http://wechat.psucs.com");
            soapMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, StandardCharsets.UTF_8.displayName());
            Name msg = soapEnvelope.createName("msg","wec",null);
            Name method = soapEnvelope.createName("testMethod","wec","http://wechat.psucs.com");
            //soapMessage.getSOAPBody().addDocument(document);

            //添加消息体以及json字符串
            SOAPBody body = soapMessage.getSOAPBody();
            body.setPrefix("soapenv");
            SOAPBodyElement bodyElement = body.addBodyElement(method);
            SOAPElement msgBody = bodyElement.addChildElement("msg","wec");
            msgBody.addNamespaceDeclaration("wec","http://wechat.psucs.com");
            SOAPElement requestData = soapFactory.createElement(rootElement);
            msgBody.addChildElement(requestData);
            // msgBody.addTextNode(judgeNull(xmlParam));
    //                SOAPElement methodElement = soapFactory.createElement(method);
    //                SOAPElement msgBody = soapFactory.createElement(msg);
    //                SOAPElement requestData = soapFactory.createElement(rootElement);
    //                msgBody.addChildElement(requestData);
    //                methodElement.addChildElement(msgBody);
    //                body.addChildElement(methodElement);
            //添加信息头内容
            SOAPHeader header = soapEnvelope.getHeader();
            header.setPrefix("soapenv");
            SOAPElement wsHeaderElm = soapFactory.createElement("HEADER", "wec", "http://wechat.psucs.com");
            SOAPElement svcnameElm = soapFactory.createElement("SVCNAME");
            wsHeaderElm.addChildElement(svcnameElm);
            header.addChildElement(wsHeaderElm);
            soapMessage.saveChanges();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            soapMessage.writeTo(bos);
            String outParam = new String(bos.toByteArray(), StandardCharsets.UTF_8.toString());
            System.out.println(outParam);
            System.out.println(StringEscapeUtils.unescapeHtml(outParam));
            System.out.println(outParam.replaceAll("ORDER", "cov:ORDER"));
            return outParam;
        } catch (SOAPException | IOException | TransformerFactoryConfigurationError e) {
            e.printStackTrace();
            return null;
        }
    }
}
